/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.inspur.edp.bef.bemanager.service.cdmparser.CdmColumnInfo;
import com.inspur.edp.bef.bemanager.service.cdmparser.CdmReader;
import com.inspur.edp.bef.bemanager.service.cdmparser.CdmTableInfo;
import com.inspur.edp.bef.bizentity.GspBizEntityElement;
import com.inspur.edp.bef.bizentity.json.element.BizElementSerializer;
import com.inspur.edp.cef.designtime.api.util.Guid;
import com.inspur.edp.das.commonmodel.collection.GspElementCollection;
import java.util.ArrayList;
import java.util.List;

public class ImportCdmService {

  private static ImportCdmService instance;
  private final String errorCode = "ImportCdmService";
  private final BizElementSerializer elementConverter;

  private ImportCdmService() {
//        CefSerializerContext tempVar = new CefSerializerContext();
//        tempVar.Mode = SerializerMode.Transfer;
    elementConverter = new BizElementSerializer();
  }

  public static ImportCdmService getInstance() {
    if (instance == null) {
      instance = new ImportCdmService();
    }
    return instance;
  }

  public final String convertToJson(String xml) {
    CdmReader reader = new CdmReader(xml);
    List<CdmTableInfo> tables = reader.getTables();

    try {
      return new ObjectMapper().writeValueAsString(tables);
    } catch (JsonProcessingException e) {
      throw new RuntimeException("cdm序列化失败", e);
    }
//		return JsonConvert.SerializeObject(tables);
  }

  /**
   * 将cdmTable中的列信息转换为be字段集合
   *
   * @param columnsJson
   * @return
   */
  public final String convertCdmTableToBizElements(String columnsJson) {
    ArrayList<CdmColumnInfo> list = readCdmColumnsInfo(columnsJson);
    GspElementCollection elements = new GspElementCollection(null);
    if (list != null && list.size() > 0) {
      for (CdmColumnInfo columnInfo : list) {
        if (columnInfo.getCode().equals("ID")) {
          continue;
        }
        elements.add(convertcdmcolumninfotoelement(columnInfo));
      }
    }
    return writeElementsJson(elements);
  }

  private java.util.ArrayList<CdmColumnInfo> readCdmColumnsInfo(String json) {

    ArrayList<CdmColumnInfo> list = null;
    try {
      ObjectMapper mapper = new ObjectMapper();
      SimpleModule module = new SimpleModule();
      mapper.registerModule(module);
      JavaType type = mapper.getTypeFactory().
          constructCollectionType(ArrayList.class, CdmColumnInfo.class);
      list = mapper.readValue(json, type);
    } catch (JsonProcessingException e) {
      throw new RuntimeException("CdmColumnInfo反序列化失败", e);
    }

//        Object tempVar = JToken.Parse(json);
//
//        var jArray = (JArray) ((tempVar instanceof JArray) ? tempVar : null);
//        if (jArray != null) {
//            for (int i = 0; i < jArray.size(); i++) {
//                JToken o = jArray[i];
//                String columnJson = o.toString();
//                Object tempVar2 = JsonConvert.DeserializeObject(columnJson, CdmColumnInfo.class);
//                CdmColumnInfo item = (CdmColumnInfo) ((tempVar2 instanceof CdmColumnInfo) ? tempVar2 : null);
//                list.add(item);
//            }
//        }
    return list;
  }

  /**
   * 获取当前字段集合
   *
   * @param elements
   * @return
   */
  private String writeElementsJson(GspElementCollection elements) {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();

    module.addSerializer(GspBizEntityElement.class, elementConverter);
    mapper.registerModule(module);
    try {
      return mapper.writeValueAsString(elements);
    } catch (JsonProcessingException e) {
      throw new RuntimeException("序列化失败", e);
    }
  }


  private GspBizEntityElement convertcdmcolumninfotoelement(CdmColumnInfo columnInfo) {
    GspBizEntityElement element = new GspBizEntityElement();
    element.setID(Guid.newGuid().toString());
    element.setCode(columnInfo.getCode());
    element.setLabelID(columnInfo.getCode());
    element.setName(columnInfo.getName());
    element.setLength(Integer.parseInt(columnInfo.getLength()));
    element.setPrecision(Integer.parseInt(columnInfo.getPrecision()));
    element.setMDataType(columnInfo.getDataType());
    element.setIsRequire(false);
    return element;

  }
}
